var express = require('express');
var httpHelper = require('../utils/httpHelper')
var xml2js = require('xml2js');
var parseString = xml2js.parseString;

var OSCAPI = require('../utils/OSCAPI')

var router = express.Router();

router.post('/login',function(req,res,next){
  var url=OSCAPI.login;
  var result={};
  console.log('login user:'+req.body.username+';'+req.body.pwd);
  var reqJson={username:req.body.username,pwd:req.body.pwd};
  httpHelper.post(url,30000,reqJson,function(err,xml,req_1,res_1){
    if(err){
        console.log(err);
    }
    console.log('response HEADERS:' + JSON.stringify(res_1.headers['set-cookie']));
    var length=res_1.headers['set-cookie'].length;
    var key =res_1.headers['set-cookie'][length-1];
    result.key=key;
    //console.log(data);
    parseString(xml, {explicitArray:false,ignoreAttrs:true},function (err, data) {
        //console.log(JSON.stringify(data));
        result.data=data;
        res.json(result);
    });

  })
});

router.post('/my_information',function(req,res,next){
  var url=[OSCAPI.my_information,'uid='+req.body.uid].join('?');
  var Cookie=['_reg_key_=7ff;',req.body.key].join(' ');
  var result={};
  console.log('Cookie:'+Cookie);
  httpHelper.get(url,30000,function(err,xml){
    if(err){
        console.log(err);
    }
    //console.log(data);
    parseString(xml, {explicitArray:false,ignoreAttrs:true},function (err, data) {
        console.log(JSON.stringify(data));
        result=data;
        res.json(result);
    });
  },'utf-8',{
    'Cookie':Cookie
    //'Cookie':'_reg_key_=7ff; oscid=npFIhaRK%2FM3RwZlW4%2FWSRbrRov5OvHEg%2FSsTgA4HGuQTWEOtvLSznRD0MlMPiKwXMDifBvGvwFHrihjCORC3pLXnEHBq6wzZ%2FPLRjaV%2FTyxbxBfh2L8Htw%3D%3D'
  })

})

router.get('/find_user',function(req,res,next){
  var url=[OSCAPI.find_user,'name='+req.query.name].join('?');
  var result={};
  httpHelper.get(url,30000,function(err,xml){
    if(err){
        console.log(err);
        next()
    }
    //console.log(data);
    parseString(xml, {explicitArray:false,ignoreAttrs:true},function (err, data) {
        //console.log(JSON.stringify(data));
        result=data;
        res.json(result);
    });

  })
})

module.exports = router;
